package firstping.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import firstping.data.QnAPersistenceManager;
import firstping.model.Customer;
import firstping.model.Domain;

@SuppressWarnings("serial")
public class AddSiteServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	
		HttpSession session = req.getSession();
		String customer = (String) session.getAttribute("customer");
		
		if(customer != null)
		{
			String[] check = new String[4];
			req.setAttribute("check", check);
			
			req.setAttribute("title", "Add site your account");
			req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site,add site");
			req.setAttribute("description", "Add site your account.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
			
			try {
				req.getRequestDispatcher("/add_site.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			resp.sendRedirect("/");
		}	
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Register success");
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		String site = req.getParameter("site");
		HttpSession session = req.getSession();
		String customer = (String) session.getAttribute("customer");
		String[] check = new String[4];
		if(customer != null)
		{
			Query query = psm.newQuery(Domain.class);
			query.setFilter("email=='"+customer+"' && name=='"+site+"'");
			@SuppressWarnings("unchecked")
			List<Domain> checks = (List<Domain>)query.execute();
			
			if(checks.size() > 0)
			{
				check[0] = "Site already exists !";
			} else {
				java.util.regex.Pattern p = java.util.regex.Pattern.compile("http://[\\w.\\-\\_]+[.][a-z]+$");
				Matcher m = p.matcher(site);
				boolean matchFound = m.matches();
			    
			    if (!matchFound)
			    {
			    	check[1] = "Website must have the form http://...";
			    }
			}
			if(check[0] == null && check[1] == null && check[2] == null && check[3] == null)
		    {			
				Query query2 = psm.newQuery(Domain.class);
				query2.setFilter("email=='"+customer+"'");
				@SuppressWarnings("unchecked")
				List<Domain> listDomain = (List<Domain>) query2.execute();
				
				Query query3 = psm.newQuery(Customer.class);
				query3.setFilter("email=='"+customer+"'");
				@SuppressWarnings("unchecked")
				List<Customer> user = (List<Customer>) query3.execute();
				if(user.size()>0)
				{
					if(user.get(0).getNumber() <= listDomain.size())
					{
						if(user.get(0).getType().equals("Trial"))
						{
							check[0] = "Your account is not upgraded, so you can add site please click on the button to perform the update account upgrade account.<br/><br/><a href='/update' class='up'>Update account</a><br/><br/>";
						} else {
							check[0] = "Your account may only add two site.";
						}
					}
				}
				if(check[0] == null)
				{
					Domain domain = new Domain();
			    	domain.setEmail(customer);
			    	int req_nb = (Integer) session.getAttribute("req");
			    	domain.setRequest(req_nb);
			    	domain.setName(site);
			    	Date update = new Date();
			    	Date up = new Date(update.getTime()+req_nb*60*1000);
			    	domain.setEndDate((Date)session.getAttribute("exp"));
			    	domain.setUpdate(up);
			    	domain.setActive("1");
			    	domain.setLastUpdateDate(update);
			    	domain.setStatus("True");
			    	psm.makePersistent(domain);
			    	req.setAttribute("success", "Add site successfully .");
				}
		    }
			req.setAttribute("check", check);
			req.setAttribute("title", "Add site your account");
			req.setAttribute("keyword", "account,monitoring domain,firstping,statistics site,add site");
			req.setAttribute("description", "Add site your account.We provide web site monitoring to webmasters. Monitor your web site is availability 24 hours a day, 7 days a week with instant email alerts and weekly web site performance statistics.");
			try {
				req.getRequestDispatcher("/add_site.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			resp.sendRedirect("/");
		}
		
	}
}
